package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: UserServiceImpl
 * Package: com.xuecheng.ucenter.service.impl
 * Description:
 *
 * @Author Endeavor-ZQB
 * @Create 2023/2/15 12:51
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    XcMenuMapper xcMenuMapper;

    @Autowired
    ApplicationContext applicationContext;

//    @Autowired
//    AuthService authService;
    
   /*/**
    * @Description  查询用户信息组成用户身份信息
    * @Param s  AuthParamsDto类型的json数据
    * @return org.springframework.security.core.userdetails.UserDetails
    **/
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        //将认证参数转为AuthParamsDto类型
        try {
            authParamsDto = JSON.parseObject(s,AuthParamsDto.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        //认证方法
        String authType = authParamsDto.getAuthType();
        AuthService authService = applicationContext.getBean(authType + "_authservice", AuthService.class);
        XcUserExt user = authService.execute(authParamsDto);

        return getUserPrincipal(user);


        //开始认证
//        authService.execute(authParamsDto);

//        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(XcUser::getUsername,s);
//        XcUser user = xcUserMapper.selectOne(queryWrapper);
    }

    /**
     * 查询用户身份
     * @param user 用户 id 主键
     * @return
     */
    public UserDetails getUserPrincipal(XcUserExt user){

        String password = user.getPassword();
        //查询用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        List<String> permissions = new ArrayList<>();
        if (xcMenus.size()<=0){
            //用户用户权限,如果不加报Cannot pass a null GrantedAuthority collection
            permissions.add("p1");
        }else {
            xcMenus.forEach(menu->{
                permissions.add(menu.getCode());
            });
        }

        //将用户权限放在XcUserExt中
        user.setPermissions(permissions);

//        String[] authorities = {"p1"};



        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转为JSON
        String userString = JSON.toJSONString(user);
        String[] authorities = permissions.toArray(new String[0]);


        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        UserDetails userDetails = User.withUsername(userString).password(password).authorities(authorities).build();

        return userDetails;
    }
}
